import Vue from 'vue'
import VueRouter from 'vue-router'
import LayoutView from '../views/LayoutView.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/layout', meta: { title: 'Welcome' } },
  {
    path: '/layout',
    name: 'layout',
    component: LayoutView,
    meta: { title: 'Welcome!' },
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('../views/home/HomeView.vue'),
      },
      {
        path: '/about',
        name: 'about',
        component: () => import('../views/about/AboutView.vue'),
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/test',
    name: 'test', 
    component: () => import('../views/testView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.isLogin === true) {
    const token = window.sessionStorage.getItem('token')
    if(token){
      next()
    }else{
      next('/login')
    }
  }else{
    next()
  }
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})
export default router
